package com.tee.live.im.core.server.handler;

import com.tee.im.interfaces.ImTokenRpc;
import com.tee.live.im.core.server.common.ChannelHandlerContextCache;
import com.tee.live.im.core.server.common.ImContextUtils;
import com.tee.live.im.core.server.common.ImMsg;
import io.netty.channel.ChannelHandlerContext;
import org.apache.dubbo.config.annotation.DubboReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

/**
 * 登出消息处理器
 *
 * @author tee
 * @date 2025/10/22
 */
@Component
public class LogoutImMsgHandler implements SimplyHandler {

    private static final Logger log = LoggerFactory.getLogger(LogoutImMsgHandler.class);

    @DubboReference
    private ImTokenRpc imTokenRpc;

    @Override
    public void handler(ChannelHandlerContext ctx, ImMsg imMsg) {
        // 登出消息处理
        log.info("登出消息处理:{}", imMsg);
        Long userId = ImContextUtils.getUserId(ctx);
        if (userId == null) {
            log.error("attr error,imMsg is {}", imMsg);
            throw new IllegalArgumentException("attr is error");
        }
        byte[] body = imMsg.getBody();
        if (body == null || body.length == 0) {
            log.error("登出消息体为空");
            ctx.close();
            throw new IllegalArgumentException("body error");
        }
        ChannelHandlerContextCache.remove(userId);
        ctx.close();

    }

}
